<?php


namespace app\admin\model\express;


use addons\third\model\Third;
use EasyWeChat\Factory;

class Subscribe
{
    protected $app = null;
    public function __construct()
    {
        $config = get_addon_config('third');
        $config = [
            'app_id'    => $config['wxapp']['app_id'],
            'secret'   => $config['wxapp']['app_secret'],
            'response_type' => 'array',
        ];
        $this->app = Factory::miniProgram($config);
    }

    public function push($user_id,$template_id,$page,$data){
        $openid = Third::where([
            'user_id' => $user_id,
            'platform' => 'wxapp',
        ])->value('openid');
        $data = [
            'template_id' => $template_id, // 所需下发的订阅模板id
            'touser' => $openid,     // 接收者（用户）的  openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => $data,
        ];
        $res = $this->app->subscribe_message->send($data);
        $sub = model('app\api\model\TemplateSub')->where([
            'user_id' => $user_id,
            'template_id' => $template_id
        ])->find();
        if($sub){
            $sub->allowField(true)->save([
                'status' => 0
            ]);
        }
        return $res;
    }
}